<template>
  <div class="bar-ranking-chart">
    <div v-show="isDrillDownChart">
      <stats-chart-empty v-show="isEmpty">
        暂无数据
      </stats-chart-empty>

      <!-- 图表 -->
      <div class="chart-header flex-space-between">
        <div class="title">{{title}}</div>
        <chart-download 
          :chart-type="chartType"
          :chart-data="chartData"
          :type="type"
          :id="id"/>
      </div>
      <div v-show="!isEmpty" :id="id" class="ranking-chart" />

      <div class="load-more">
        <el-button v-show="hasNextPage && !isEmpty" @click="categoryMore" type="text">加载更多</el-button>
        <span v-show="!hasNextPage && !isEmpty" class="color9a9a9a" type="text" disabled>数据加载完毕</span>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts5 from 'echarts5';
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue';
import { useBarRankingChartData } from './useChartData';
/* component */
import StatsChartEmpty from '@src/modules/report/common/StatsChartEmpty.vue';
import {
  ChartDownload
} from './common/index';
/* mixins */
import ChartsMixin from '@src/modules/report/managementReport/charts/components/mixins/charts.mixins';
/* util */
import { isArray } from '@src/util/type'
import { isOpenData } from '@src/util/platform';
export default {
  name: 'bar-ranking-chart',
  mixins: [ChartsMixin],
  components: {
    StatsChartEmpty,
    ChartDownload
  },
  props: {
    chartType: {
      type: String,
			default: ''
    },
    chartData: {
      type: Array,
      default: () => []
    },
    title: {
      type: String,
      default: ''
    },
    id: {
      type: String,
      default: ''
    },
    hasNextPage: {
      type: Boolean,
      default: true
    },
    // 显示下钻图表
    isDrillDown: {
      type: Boolean,
      default: false
    },
    typeValue: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
			default: ''
    },
  },
  setup(props, { emit }) {
    const chart = ref(null)
    const isEmpty = ref(false)
    const isDrillDownChart = ref(true)
    
    const drawChart = () => {
      let chartData = props.chartData;

      chartData = props.chartData.sort((a,b) => b.value - a.value) || [];
      
      const { data, yAxisData } = useBarRankingChartData(chartData, props.typeValue);

      if (props.id === 'staffIncome' || props.id === 'staffProfit') {
        isDrillDownChart.value = props.isDrillDown
      }

      if (isArray(data?.value)) {
        isEmpty.value = data.value.every(item => !item)
      }

      if (!props.chartData?.length) isEmpty.value = true
      if (isEmpty.value) return

      let start = 0
      let end = yAxisData?.value.length - 1
      if(yAxisData?.value.length > 10) start = end - 9

      const buildFormatter = value => {
        if (props.id === 'TeamProfit' || props.id === 'staffProfit') {
          return `¥${value?.data?.value} ${value?.data?.profitRate}`
        }
        if(props.typeValue){
          return `¥${value?.data}`;
        }
        return `¥${value?.data?.value}`
      }

      let yAxisMap = {
        type: 'category',
        data: yAxisData.value,
        inverse: true,
        axisLabel: {
          formatter(value) {
            if (value.length > 4) {
              return `${value.substring(0, 4) }...`;
            } 
            return value;
            
          }
        }
      }
      if (isOpenData && (props.id === 'staffIncome' || props.id === 'staffProfit')) {
        yAxisMap = {
          type: 'category',
          data: yAxisData.value,
          inverse: true,
        }
      }
      const dataOption = {
        grid: {
          top: 20,
          left: 80,
          right: 80,
        },
        dataZoom: [
          {
            type: 'inside'
          },
          {
            type: 'slider',
            yAxisIndex: [0]
          }
        ],
        xAxis: {
          type: 'value'
        },
        yAxis: yAxisMap,
        series: [
          {
            barMaxWidth: '60px',
            data: data.value,
            type: 'bar',
            stack: 'Total',
            label: {
              show: true,
              position: 'insideLeft',
              formatter: buildFormatter
            },
          }
        ]
      }
      chart.value.clear()
      chart.value.setOption(dataOption)
      nextTick(() => {
        chart.value.resize()
      })
    }

    const initChart = () => {
      chart.value = echarts5.init(document.getElementById(props.id), 'shb')
      if (props.id !== 'staffIncome' || props.id !== 'staffProfit') {
        chart.value.on('click', value => {
          emit('fetchTableData', value)
        })
      }
      
      drawChart()
    }

    const chartData = computed(() => {
			return props.chartData
		})
    const isShowDrillDown = computed(() => {
      return props.isDrillDown
    })
		watch([chartData, isShowDrillDown], (n,o) => {
			drawChart()
		})
    
    const categoryMore = () => {
      emit('categoryMore')
    }
    onMounted(() => {
      initChart()
    })
    onUnmounted(() => {
      if (!chart.value) return
      chart.value = null
    })
    return {
      isEmpty,
      isDrillDownChart,
      chart,
      initChart,
      categoryMore
		}
  },
};
</script>
<style lang="scss" scoped>
.bar-ranking-chart {
  position: relative;
  .chart-header {
    height: 30px;
    line-height: 30px;
    .title {
      font-weight: bold;
    }
  }
  .load-more {
    height: 40px;
    line-height: 40px;
  }
}
.flex-space-between {
  display: flex;
  justify-content: space-between;
}
.ranking-chart {
	width: 100%;
  height: 500px;
}
.color9a9a9a{
  color: #9a9a9a;
}
</style>
<style lang="scss">
  .ranking-chart {
    & > div {
      width: 100% !important;
    }
  }
</style>
